package com.xhh.greymall.product.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.xhh.greymall.product.entity.AttrGroupEntity;
import com.xhh.greymall.product.entity.CategoryBrandRelationEntity;
import com.xhh.greymall.product.service.CategoryBrandRelationService;
import com.xhh.greymall.product.vo.Catalog2VO;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.cache.annotation.Caching;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.lang.reflect.Array;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhh.common.utils.PageUtils;
import com.xhh.common.utils.Query;

import com.xhh.greymall.product.dao.CategoryDao;
import com.xhh.greymall.product.entity.CategoryEntity;
import com.xhh.greymall.product.service.CategoryService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import sun.rmi.runtime.Log;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Autowired
    CategoryBrandRelationService categoryBrandRelationService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    RedissonClient redisson;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public List<CategoryEntity> listWithTree() {
        List<CategoryEntity> entities = baseMapper.selectList(null);

        // 找到一级菜单
        List<CategoryEntity> collect = entities.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == 0
        ).map((menu) -> {
            menu.setChild(getChildren(menu, entities));
            return menu;
        }).sorted((menu1, menu2) -> {
            // 菜单排序
            return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
        }).collect(Collectors.toList());


        return collect;
    }

    @Override
    public void removeMenuByIds(List<Long> asList) {
        // TODO 检查当前的菜单，是否被其他地方引用
        baseMapper.deleteBatchIds(asList);

        // 开发中多使用逻辑删除，mybatis-plus中可以定义

    }

    // 查询某个菜单id的父，子..如[2,25,225]
    @Override
    public Long[] findCatelogPath(Long catelogId) {
        List<Long> path = new ArrayList<>();
        List<Long> paths = findParentPath(path, catelogId);

        Collections.reverse(paths);
        return paths.toArray(new Long[paths.size()]);
    }

    /**
     * 级联更新其他关联字段
     * @CacheEvict:失效模式
     * 同时进行多种缓存操作@Caching
     * 指定删除分区下的所有数据@CacheEvict(value = "category", allEntries = true)
     * 存储同一类型的数据，都可以指定成同一个分区。
     * @param category
     */
//    @Caching(evict = {
//            @CacheEvict(value = "category", key = "'getCatLevelOneList'"),
//            @CacheEvict(value = "category", key = "'getCatalogJson'")
//    })
    @CacheEvict(value = "category", allEntries = true)
    @Transactional
    @Override
    public void updateDetail(CategoryEntity category) {
        this.updateById(category);
        categoryBrandRelationService.updateCategory(category.getCatId(), category.getName());
    }

    // 每一个需要缓存的数据我们都来指定要放到哪个名字的缓存【缓存的分区（按照业务类型分）】
    @Cacheable(value = {"category"}, key = "#root.method.name", sync = true) //代表当前方法的结果需要缓存，如果缓存中有，方法不会调用，如果缓存中没有，调用方法将结果放入缓存
    @Override
    public List<CategoryEntity> getCatLevelOneList() {
        System.out.println("getCatLevelOneList...");
        //long l = System.currentTimeMillis();
        List<CategoryEntity> categoryEntityList = baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", 0));
//        System.out.println(categoryEntityList);
        return categoryEntityList;
    }

    @Cacheable(value = "category", key = "#root.methodName")
    @Override
    public Map<String, List<Catalog2VO>> getCatalogJson() {
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //1、查出所有一级分类
        List<CategoryEntity> catLevelOneList = getParent_cid(selectList, 0L);
        //封装数据
        Map<String, List<Catalog2VO>> catalogJson = catLevelOneList.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //查询一级分类的子分类->二级分类
            List<CategoryEntity> catLevelTwoList = getParent_cid(selectList, v.getCatId());
            List<Catalog2VO> catalog2VOS = null;
            if (catLevelTwoList != null) {
                catalog2VOS = catLevelTwoList.stream().map(catLevelTwo -> {
                    //封装成指定格式
                    Catalog2VO catalog2VO = new Catalog2VO(v.getCatId().toString(), null, catLevelTwo.getCatId().toString(), catLevelTwo.getName());
                    //查询二级分类的子分类->三级分类
                    List<CategoryEntity> catLevelThreeList = getParent_cid(selectList, catLevelTwo.getCatId());
                    if (catLevelThreeList != null) {
                        List<Catalog2VO.Catalog3> collect = catLevelThreeList.stream().map(catLevelThree -> {
                            //封装成指定格式
                            return new Catalog2VO.Catalog3(catLevelTwo.getCatId().toString(), catLevelThree.getCatId().toString(), catLevelThree.getName());
                        }).collect(Collectors.toList());
                        catalog2VO.setCatalog3List(collect);
                    }
                    return catalog2VO;
                }).collect(Collectors.toList());
            }
            return catalog2VOS;
        }));

        return catalogJson;
    }

    //如果产生堆外内存溢出，没有及时释放 OufOfDirectMemoryError
    // 解决方案：升级lettue客户端(目前的版本，我的不会出现溢出)
    //不能使用：通过-Dio.netty.maxDirectMemory
    public Map<String, List<Catalog2VO>> getCatalogJson2() {
        /**
         * 1、空结果缓存：解决缓存穿透
         * 2、设置过期时间（加随机值）：解决缓存雪崩
         * 3、加锁：解决缓存击穿
         */
        //1、加入缓存，缓存中存的数据是json字符串
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (StringUtils.isEmpty(catalogJSON)) {
            //2、缓存中没有数据，查询数据库
            System.out.println("缓存中没有数据，准备查询数据库");
            Map<String, List<Catalog2VO>> catalogJsonFromDb = getCatalogJsonFromDbWithRedisLock();

            return catalogJsonFromDb;
        }
        System.out.println("缓存中有数据，直接返回");
        //将catalogJSON转为对象
        Map<String, List<Catalog2VO>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2VO>>>() {
        });
        return result;
    }

    /**
     * 缓存里面的数据如何和数据库保持一致
     * 缓存数据一致性
     * 1、双写模式
     * 2、失效模式
     * @return
     */
    public Map<String, List<Catalog2VO>> getCatalogJsonFromDbWithRedissonLock() {

        //1、锁的名字，锁的粒度，越细越快。
        //锁的粒度：具体缓存的某个数据，11-号商品；product-11-lock,product-12-lock
        RLock lock = redisson.getLock("CatalogJson-lock");
        lock.lock();


        Map<String, List<Catalog2VO>> dataFromDb;
        try {
            dataFromDb = getDataFromDb();
        } finally {
            lock.unlock();
        }

        return dataFromDb;

    }


    //从数据库查询并封装分类数据->使用分布式锁
    public Map<String, List<Catalog2VO>> getCatalogJsonFromDbWithRedisLock() {

        //1、占分布式锁，去redis占坑
        String uuid = UUID.randomUUID().toString();
        Boolean lock = redisTemplate.opsForValue().setIfAbsent("lock", uuid, 300, TimeUnit.SECONDS);
        if (lock) {
            System.out.println("获取分布式锁成功");
            //设置过期时间
            //redisTemplate.expire("lock", 30, TimeUnit.SECONDS);
            //加锁成功...执行业务
            Map<String, List<Catalog2VO>> dataFromDb;
            try {
                dataFromDb = getDataFromDb();
            } finally {
                String script = "if redis.call('get',KEYS[1]) == ARGV[1] then return redis.call('del',KEYS[1]) else return 0 end";
                //删除锁
                Long lock1 = redisTemplate.execute(new DefaultRedisScript<Long>(script, Long.class), Arrays.asList("lock"), uuid);
            }

            //获取值对比，对比成功删除，原子操作
//            String lockValue = redisTemplate.opsForValue().get("lock");
//            if(uuid.equals(lockValue)){
//                //删除我自己的锁
//                redisTemplate.delete("lock");
//            }

            return dataFromDb;
        } else {
            System.out.println("获取分布式锁失败...等待重试");
            //加锁失败...重试 synchronized ()
            //休眠100ms重试
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            return getCatalogJsonFromDbWithRedisLock(); //自旋的方式
        }


    }

    private Map<String, List<Catalog2VO>> getDataFromDb() {
        //得到锁后，在去查缓存，如果没有才需要继续查
        String catalogJSON = redisTemplate.opsForValue().get("catalogJSON");
        if (!StringUtils.isEmpty(catalogJSON)) {
            //将catalogJSON转为对象
            Map<String, List<Catalog2VO>> result = JSON.parseObject(catalogJSON, new TypeReference<Map<String, List<Catalog2VO>>>() {
            });
            return result;
        }
        System.out.println("查询了数据库.....");
        /**
         * 优化查询
         * 1、将数据库的多次查询变为一次
         */
        // 查询全部
        List<CategoryEntity> selectList = baseMapper.selectList(null);

        //1、查出所有一级分类
        List<CategoryEntity> catLevelOneList = getParent_cid(selectList, 0L);
        //封装数据
        Map<String, List<Catalog2VO>> catalogJson = catLevelOneList.stream().collect(Collectors.toMap(k -> k.getCatId().toString(), v -> {
            //查询一级分类的子分类->二级分类
            List<CategoryEntity> catLevelTwoList = getParent_cid(selectList, v.getCatId());
            List<Catalog2VO> catalog2VOS = null;
            if (catLevelTwoList != null) {
                catalog2VOS = catLevelTwoList.stream().map(catLevelTwo -> {
                    //封装成指定格式
                    Catalog2VO catalog2VO = new Catalog2VO(v.getCatId().toString(), null, catLevelTwo.getCatId().toString(), catLevelTwo.getName());
                    //查询二级分类的子分类->三级分类
                    List<CategoryEntity> catLevelThreeList = getParent_cid(selectList, catLevelTwo.getCatId());
                    if (catLevelThreeList != null) {
                        List<Catalog2VO.Catalog3> collect = catLevelThreeList.stream().map(catLevelThree -> {
                            //封装成指定格式
                            return new Catalog2VO.Catalog3(catLevelTwo.getCatId().toString(), catLevelThree.getCatId().toString(), catLevelThree.getName());
                        }).collect(Collectors.toList());
                        catalog2VO.setCatalog3List(collect);
                    }
                    return catalog2VO;
                }).collect(Collectors.toList());
            }
            return catalog2VOS;
        }));

        //3、查询到后放入缓存，将对象转为json
        String jsonString = JSON.toJSONString(catalogJson);
        redisTemplate.opsForValue().set("catalogJSON", jsonString, 1, TimeUnit.DAYS);

        return catalogJson;
    }

    //从数据库查询并封装分类数据->使用本地锁
    public Map<String, List<Catalog2VO>> getCatalogJsonFromDbWithLocalLock() {
        //使用锁解决缓存击穿
        //TODO 本地锁：synchronized，JUC(lock) 在分布式情况下，想要锁住所有，必须使用分布式锁
        synchronized (this) {
            //得到锁后，在去查缓存，如果没有才需要继续查
            return getDataFromDb();
        }
    }

    private List<CategoryEntity> getParent_cid(List<CategoryEntity> selectList, Long parent_cid) {
        List<CategoryEntity> collect = selectList.stream().filter(item -> {
            return item.getParentCid() == parent_cid;
        }).collect(Collectors.toList());
        return collect;
        //return baseMapper.selectList(new QueryWrapper<CategoryEntity>().eq("parent_cid", v.getCatId()));
    }

    // 255,25,2
    private List<Long> findParentPath(List<Long> list, Long catelogId) {
        // 收集当前节点id
        list.add(catelogId);
        CategoryEntity byId = this.getById(catelogId);
        if (byId.getParentCid() != 0) {
            findParentPath(list, byId.getParentCid());
        }
        return list;
    }

    // 找到一级菜单下的子菜单,递归查找菜单的所有子菜单
    private List<CategoryEntity> getChildren(CategoryEntity root, List<CategoryEntity> all) {
        List<CategoryEntity> collect = all.stream().filter(categoryEntity ->
                categoryEntity.getParentCid() == root.getCatId()
        )
                .map((menu) -> {
                    // 找到子菜单
                    menu.setChild(getChildren(menu, all));
                    return menu;
                })
                .sorted((menu1, menu2) -> {
                    // 菜单排序
                    return (menu1.getSort() == null ? 0 : menu1.getSort()) - (menu2.getSort() == null ? 0 : menu2.getSort());
                })
                .collect(Collectors.toList());

        return collect;
    }
}